package com.season.seasonStudy.javase.j_008_database;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Dao<T> {
	Connection conn = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	private final String DRIVER = "oracle.jdbc.OracleDriver";
	private final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";

	public Object chaone(String sql, Object condition, T t) {
		T obj = null;
		try {
			Class cla = t.getClass();
			obj =(T)cla.newInstance();
			ps = getConn().prepareStatement(sql);
			ps.setObject(1, condition);
			rs = ps.executeQuery();

			Method[] methods = cla.getDeclaredMethods();
			Field[] fields = cla.getDeclaredFields();

			while (rs.next()) {
				for (int i = 0; i < fields.length; i++) {
					
					Object data = rs.getObject(fields[i].getName());
					
					for (int j = 0; j < methods.length; j++) {
						
						String methodName = methods[j].getName();

						if (methodName.startsWith("set")) {
							
							String m = methods[j].getName().substring(3);
							String f = fields[i].getName();
							if (m.equalsIgnoreCase(f)) {
								System.out.println("methods[i]---"
										+ methods[j].getName());
								System.out.println("fields[i]---"
										+ fields[i].getName());
								methods[i].invoke(obj, data);
							}
						}
					}
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeAll(conn, ps, rs);
		}
		return null;
	}

	public Connection getConn() {
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, "jijie", "123");
			return conn;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pstmt != null) {
				rs.close();
			}
			if (conn != null) {
				rs.close();
			}
		} catch (Exception e) {
		}
	}

}